package com.ncd.form.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncd.common.core.domain.Ztree;
import com.ncd.common.core.text.Convert;
import com.ncd.common.utils.StringUtils;
import com.ncd.common.utils.uuid.IdUtils;
import com.ncd.form.domain.FormDict;
import com.ncd.form.domain.RecordItm;
import com.ncd.form.mapper.FormDictMapper;
import com.ncd.form.service.IFormDictService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表单字典Service业务逻辑处理
 *
 * @author tree_new_bee
 */
@Service
public class FormDictServiceIml extends ServiceImpl<FormDictMapper, FormDict> implements IFormDictService {


    @Override
    public List<FormDict> queryList(FormDict formDict) {

        LambdaQueryWrapper<FormDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotNull(formDict.getDictParent()),FormDict::getDictParent,formDict.getDictParent());
        wrapper.eq(StrUtil.isNotBlank(formDict.getDictType()),FormDict::getDictType,formDict.getDictType());
        wrapper.eq(StrUtil.isNotBlank(formDict.getDictDataSet()),FormDict::getDictDataSet,formDict.getDictDataSet());
        wrapper.like(ObjectUtil.isNotNull(formDict.getDictCode()),FormDict::getDictCode,formDict.getDictCode());
        wrapper.like(ObjectUtil.isNotNull(formDict.getDictTitle()),FormDict::getDictTitle,formDict.getDictTitle());
        return this.list(wrapper);
    }

    @Override
    public FormDict selectDictByParent(Long dictId, Map<String, List<RecordItm>> recordItmMap) {
        FormDict dict=this.baseMapper.selectById(dictId);

        List<FormDict> subDictList = this.selectSubDict(dictId,dict.getDictLinkId());
        if("table".equals(dict.getDictType())){

            List<FormDict> coulmnDicts=this.selectSubDict(subDictList.get(0).getDictId(),null);  //行字典
            for(FormDict columnDict:coulmnDicts){
                List<FormDict> coulmnSubDicts=this.selectSubDict(columnDict.getDictId(),columnDict.getDictLinkId());  //行下的列字典
                columnDict.setDicts(coulmnSubDicts);
            }

            if((recordItmMap!=null)&&(recordItmMap.size()>0)){
                Map<String,RecordItm> trMap=new HashMap<>();
                for(Map.Entry<String, List<RecordItm>> entry : recordItmMap.entrySet()){
                    if(entry.getKey().split("-").length<=1) continue;
                    String rowKey=entry.getKey().split("-")[1];
                    if(StringUtils.isNotEmpty(rowKey)){
                        trMap.put(rowKey,null);
                    }
                }
                //以前填写过的记录
                for(Map.Entry<String, RecordItm> entry : trMap.entrySet()){
                    String mapKey=entry.getKey();
                    FormDict rowRecordItmDict=new FormDict();
                    rowRecordItmDict.setRowKey("-"+mapKey);
                    dict.getDicts().add(rowRecordItmDict);
                    for(FormDict coulmnDict:coulmnDicts){
                        FormDict newColumnDict=new FormDict();
                        newColumnDict.setDictId(coulmnDict.getDictId());
                        newColumnDict.setDictType(coulmnDict.getDictType());
                        newColumnDict.setDictTitle(coulmnDict.getDictTitle());
                        newColumnDict.setDictCode(coulmnDict.getDictCode());
                        newColumnDict.setDictWidth(coulmnDict.getDictWidth());
                        for(FormDict coulmnSubDict:coulmnDict.getDicts()){
                            FormDict newColumnSubDict=new FormDict();
                            newColumnSubDict.setDictId(coulmnSubDict.getDictId());
                            newColumnSubDict.setDictCode(coulmnSubDict.getDictCode());
                            newColumnSubDict.setDictTitle(coulmnSubDict.getDictTitle());
                            newColumnSubDict.setDictWidth(coulmnSubDict.getDictWidth());
                            newColumnSubDict.setDictScore(coulmnSubDict.getDictScore());
                            newColumnDict.getDicts().add(newColumnSubDict);
                        }
                        setDictValue(newColumnDict,recordItmMap,mapKey);
                        rowRecordItmDict.getDicts().add(newColumnDict);
                    }

                }
            }else{
                //新增加空行
                FormDict rowDict=new FormDict();
                rowDict.setRowKey("-"+ IdUtils.fastUUID());
                rowDict.setDicts(coulmnDicts);
                dict.getDicts().add(rowDict);
            }
        }else if("divtable".equals(dict.getDictType())){
            //tr
            dict.setDicts(subDictList);
            subDictList.forEach(dict1 -> {
                //td
                dict1.setDicts(this.selectSubDict(dict1.getDictId(),dict1.getDictLinkId()));

                dict1.getDicts().forEach(dict2 -> {
                    //字典元素
                    dict2.setDicts(this.selectSubDict(dict2.getDictId(),dict2.getDictLinkId()));
                    dict2.getDicts().forEach(dict3 -> {
                        if(ObjectUtil.isNotNull(dict3.getDictScore())){
                            dict3.setDisplayTitle(dict3.getDictTitle()+"("+dict3.getDictScore().intValue()+"分)");
                        }else{
                            dict3.setDisplayTitle(dict3.getDictTitle());
                        }
                        setDictValue(dict3,recordItmMap,"");
                    });
                    setDictValue(dict2,recordItmMap,"");
                });
            });
        }else{
            dict.setDicts(subDictList);
            setDictValue(dict,recordItmMap,"");
        }
        return dict;
    }

    private void setDictValue(FormDict dict,Map<String,List<RecordItm>> recordItmMap,String rowKey){

        String key=dict.getDictId().toString()+"-"+rowKey;

        if(recordItmMap.containsKey(key)){
            List<RecordItm> recordItms=recordItmMap.get(key);
            if(("radio".equals(dict.getDictType()))||("checkbox".equals(dict.getDictType()))||("select".equals(dict.getDictType()))){
                for(RecordItm recordItm:recordItms){
                    if(rowKey.equals(StringUtils.nvl(recordItm.getRowKey(),""))){
                        for(FormDict dict1:dict.getDicts()){
                            if("checkbox".equals(dict.getDictType())){
                                List<Long> values= Convert.toLongList(recordItm.getValueDict());
                                for(Long valueDict:values){
                                    if(ObjectUtil.isNotNull(valueDict)){
                                        if(valueDict.equals(dict1.getDictId())){
                                            dict1.setRecordItm(recordItm);
                                        }
                                    }
                                }
                            }else{
                                if(ObjectUtil.isNotNull(recordItm.getValueDict())) {
                                    if(recordItm.getValueDict().equals(dict1.getDictId().toString())){
                                        dict1.setRecordItm(recordItm);
                                    }
                                }
                            }
                        }
                    }
                }
            }else{
                if(StrUtil.isNotBlank(recordItms.get(0).getValue())){
                    dict.setRecordItm(recordItms.get(0));
                }
            }
        }
    }

    /**
     * 查询表单字典树
     *
     * @param parent 表单字典
     * @return 所有表单字典
     */
    @Override
    public List<Ztree> selectDictTree(Long parent) {

        List<FormDict> dictList =new ArrayList<>();
        dictSub(parent,dictList);
        List<Ztree> ztrees = initZtree(dictList);
        return ztrees;
    }

    @Override
    public  List<FormDict> selectSubDict(Long parent, Long linkId) {
        if(ObjectUtil.isNotNull(linkId)){
            return this.list(Wrappers.lambdaQuery(FormDict.class).eq(FormDict::getDictParent,linkId));
        }else{
            return this.list(Wrappers.lambdaQuery(FormDict.class).eq(FormDict::getDictParent,parent));
        }
    }

    @Override
    public List<FormDict> selectDictByLink(Long linkId) {
        return this.list(Wrappers.lambdaQuery(FormDict.class).eq(FormDict::getDictLinkId,linkId));
    }

    private void dictSub(Long parent, List<FormDict> dictList){
        List<FormDict> subDictList = this.selectSubDict(parent,null);
        for(FormDict dict:subDictList){
            dictList.add(dict);
            dictSub(dict.getDictId(),dictList);
        }
    }

    /**
     * 对象转菜单树
     *
     * @param dictList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FormDict> dictList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (FormDict dict : dictList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(dict.getDictId());
            ztree.setpId(dict.getDictParent());
            ztree.setName(dict.getDictTitle());
            ztree.setTitle(dict.getDictTitle());
            ztrees.add(ztree);
        }
        return ztrees;
    }
}
